package top.yuzt.noticeserver.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.server.HttpServerResponse;
import org.junit.Test;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.yuzt.noticeserver.entity.Messagefiles;
import top.yuzt.noticeserver.service.impl.MessagefilesServiceImpl;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
@RestController
@RequestMapping("/files")
public class FileController {
    private MessagefilesServiceImpl messagefilesService;
    private final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "Local_files";
    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        String orgFilename = file.getOriginalFilename();
        String mainFilename = FileUtil.mainName(orgFilename);
        String mainFiletype = FileUtil.extName(orgFilename);

        File parenFile = new File(ROOT_PATH);
        if(!parenFile.exists()){
            parenFile.mkdirs();
        }
        orgFilename = System.currentTimeMillis() + "_" ;//改名后的文件名
        String realname = orgFilename + "." +mainFiletype;//文件+文件后缀
        File saveFile = new File(ROOT_PATH + File.separator + realname);
        file.transferTo(saveFile);
        String url = "http://localhost:8080/" + "Local_files/" + realname;
        return url;
    }

    @GetMapping("/download/{filename}")
    public void download(@PathVariable String filename, HttpServletResponse response) throws IOException {
            String filePath = ROOT_PATH + File.separator +filename;
            if (!FileUtil.exist(filePath)){
                return;
            }
            byte[] bytes = FileUtil.readBytes(filePath);
         ServletOutputStream outputStream = response.getOutputStream();
         outputStream.write(bytes);
         outputStream.flush();
         outputStream.close();

    }


}
